package com.matrix.kernel.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Properties;

/**
 * Created by chenxg on 2016/6/2.
 */
public class ConfigurationManager {

    /**
     * 错误日志
     */
    protected final static Log logger = LogFactory.getLog(ConfigurationManager.class);

    /**
     * 配置文件加载项
     */
    public static final Properties PROPERTIES = new Properties();


    /**
     *
     */
    static {
        loadProperties();
    }


    /**
     * 载入配置项
     * !确保配置项的实例，不被代码更改
     */
    public static void loadProperties() {
        Properties properties;
        URL url = ConfigurationManager.class.getProtectionDomain().getCodeSource().getLocation();
        String filePath = null;
        try {
            filePath = URLDecoder.decode(url.getPath(), "utf-8");
        } catch (Exception e) {
            logger.warn(e);
        }
        if (filePath.endsWith(".jar")) {
            if (OSinfo.isLinux())
                filePath = filePath.substring(0, filePath.lastIndexOf("/lib") + 1);
            else if (OSinfo.isWindows())
                filePath = filePath.substring(1, filePath.lastIndexOf("/lib") + 1);
            filePath = filePath + "classes";
        }
        filePath += "/config.properties";
        try {
            InputStream inputStream = new FileInputStream(filePath);
            PROPERTIES.load(inputStream);
            inputStream.close();
        } catch (IOException e) {
            logger.error("无法加载配置文件：filepath: " + filePath, e);
        }
        return;
    }


    /**
     * 获得配置项
     *
     * @param key
     * @return
     */
    public static String get(String key) {
        return PROPERTIES.getProperty(key);
    }
}
